package com.fruit.service.fruit;

import com.fruit.bean.constant.factory.PageFactory;
import com.fruit.bean.dto.fruit.FruitSellRequestInfoDto;
import com.fruit.bean.entity.fruit.FruitSellRequestInfo;
import com.fruit.bean.entity.fruit.FruitStockInfo;
import com.fruit.bean.enumeration.fruit.FruitSellReqResEnum;
import com.fruit.bean.vo.front.Rets;
import com.fruit.bean.vo.query.DynamicSpecifications;
import com.fruit.dao.fruit.FruitSellRequestRepository;
import com.fruit.dao.fruit.FruitStockRepository;
import com.fruit.dao.fruit.FruitTypeRepository;
import com.fruit.dao.system.UserRepository;
import com.fruit.service.BaseService;
import com.fruit.utils.BigDecimalUtils;
import com.fruit.utils.factory.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class FruitSellRequestService extends BaseService<FruitSellRequestInfo,Long, FruitSellRequestRepository> {

    @Autowired
    private FruitStockRepository stockRepository;

    @Autowired
    private FruitSellRequestRepository sellRequestRepository;

    @Autowired
    private FruitTypeRepository typeRepository;

    @Autowired
    private UserRepository userRepository;

    public Object addSellRequest(FruitSellRequestInfo fruitSellRequestInfo){
        //判断库存是否足够
        Optional<FruitStockInfo> fruitStockInfoOptinal = stockRepository.findById(fruitSellRequestInfo.getFruitStockId());
        FruitStockInfo fruitStockInfo = fruitStockInfoOptinal.get();
        if(fruitStockInfo.getFruitStockNumber() < fruitSellRequestInfo.getFruitSellNumber()){
            //库存不足，返回错误信息
            return Rets.failure("库存不足!");
        }

        //库存足够保存申请信息
        sellRequestRepository.save(fruitSellRequestInfo);
        return Rets.success();
    }

    /**
     * 管理员获取代卖申请（未许可 > 许可 > 不许可）
     * @return
     */
    public Page<FruitSellRequestInfoDto> list(){
        Page<FruitSellRequestInfo> page = new PageFactory().defaultPage();
        Page<FruitSellRequestInfoDto> pageRes = new PageFactory().defaultPage();
        Pageable pageable;
        if (page.getSort() != null) {
            pageable = PageRequest.of(page.getCurrent() - 1, page.getSize(), page.getSort());
        } else {
            pageable = PageRequest.of(page.getCurrent() - 1, page.getSize(), Sort.Direction.DESC, "id");
        }
        Specification<FruitSellRequestInfo> specification = DynamicSpecifications.bySearchFilter(page.getFilters(),
                sellRequestRepository.getDataClass());
        org.springframework.data.domain.Page<FruitSellRequestInfo> pageResult =
                sellRequestRepository.findAll(specification, pageable);
        pageRes.setTotal(Integer.valueOf(pageResult.getTotalElements() + ""));
        List<FruitSellRequestInfo> sellRequestInfoList = pageResult.getContent();
        List<FruitSellRequestInfoDto> sellRequestInfoDtoList = convertSellRequestList(sellRequestInfoList);
        pageRes.setRecords(sellRequestInfoDtoList);
        return pageRes;
    }

    public List<FruitSellRequestInfoDto> list(Long userId){
        List<FruitSellRequestInfo> sellRequestInfoList = sellRequestRepository.findByUserIdOrderByFruitSellRequestTimeDesc(userId);
        return convertSellRequestList(sellRequestInfoList);
    }

    private List<FruitSellRequestInfoDto> convertSellRequestList(List<FruitSellRequestInfo> sellRequestInfoList){
        List<FruitSellRequestInfoDto> resList = new ArrayList<>();
        for(FruitSellRequestInfo sellRequestInfo : sellRequestInfoList){
            FruitSellRequestInfoDto sellRequestInfoDto = new FruitSellRequestInfoDto();
            FruitStockInfo stockInfo = stockRepository.getOne(sellRequestInfo.getFruitStockId());
            sellRequestInfoDto.setFruitName(typeRepository.getOne(stockInfo.getFruitTypeId()).getFruitTypeName());
            sellRequestInfoDto.setFruitSellRequestId(sellRequestInfo.getId());
            sellRequestInfoDto.setFruitNumber(sellRequestInfo.getFruitSellNumber());
            sellRequestInfoDto.setRequestResult(sellRequestInfo.getFruitSellRequestResult());
            sellRequestInfoDto.setSellHighPrice(sellRequestInfo.getFruitHighPrice());
            sellRequestInfoDto.setSellLowPrice(sellRequestInfo.getFruitLowPrice());
            sellRequestInfoDto.setSellPrice(sellRequestInfo.getFruitSellPrice());
            sellRequestInfoDto.setLastPrice(sellRequestInfo.getFruitLastPrice());
            sellRequestInfoDto.setSellRequestUser(userRepository.getOne(stockInfo.getUserId()).getAccount());
            for(FruitSellReqResEnum sellReqResEnum : FruitSellReqResEnum.values()){
                if(sellReqResEnum.getCode().equals(sellRequestInfoDto.getRequestResult())){
                    sellRequestInfoDto.setRequestResStr(sellReqResEnum.getMsg());
                    break;
                }
            }

            resList.add(sellRequestInfoDto);
        }
        return resList;
    }
}
